var generator = require('../generator/generator');
var item = require('../model/item');

exports.addItem = function(req, res, connection) {
	var sendData = req.body;
	// console.log("addItem---sendData:", sendData);
	item.insertItem(connection, sendData, function(info) {
		// console.log("addItem--info", info);
		res.send("选项信息添加成功！");
	});
};

exports.updateItem = function(req, res, connection) {
	var sendData = req.body;
	item.updateItem(connection, sendData, function(info) {
		res.send("选项信息更新成功！");
	});
};

exports.selAll = function(req, res, connection) {
	var total = req.query.total;
	var index = req.query.index;
	var keyword = req.query.keyword;
	var begin = total * (index - 1);
	var end = total * index - 1;
	// console.log("keyword=" + keyword);
	item.selByKeyWord(connection, keyword, function(rows) {
		var itemData = [];
		var k = 0; 
		for(var i = begin; i < end + 1; i++) {
			if(i < rows.length) {
				itemData[k] = rows[i];
				k++;
			}
		}
		var sendData = {
			data: itemData,
			count: rows.length
		}
		res.send(sendData);
	});
};


//校验选项信息是否重复
exports.checkItem = function(req, res, connection) {
	// var sendData = req.params['sendData'] + '';
	var sendData = req.query.sendData;
	var dataJson = JSON.parse(sendData);
	// console.log("checkItem--dataJson:", dataJson);
	var urlType = dataJson.urlType;
	/*
	同种类型的选项不能有相同的显示值
	选项的值必须唯一
	*/
	var sendResult = "true";
	item.selByShow(connection, dataJson, function(rows) {
		if(rows != null && rows.length != 0) {
			// console.log("urlType:"+urlType);
			if(urlType == "put") {
				if(rows[0].id != dataJson.id) {
					sendResult = "showValue";
				}
			}else{
				sendResult = "showValue";
			}
			res.send(sendResult);
		}else{
			item.selByValue(connection, dataJson.value, function(results) {
				if(results != null && results.length != 0) {
					if(urlType == "put") {
						if(results[0].id != dataJson.id) {
							sendResult = "value";
						}
					}else{
						sendResult = "value";
					}
				}
				res.send(sendResult);
			});
		}
	});
	
};

exports.delItem = function(req, res, connection) {
	var id = req.query.id;
	// console.log("delItem--id=" + id);
	item.delItem(connection, id, function(result) {
		res.send("success");
	})
};

exports.selectAll = function(req,res,connection){
	item.selAll(connection,function(data){
		res.send(data);
	});
};

exports.accessChange = function(req, res, connection) {
	var accessData = req.body.accessData;
	item.updateAccess(connection, accessData, function(result) {
		res.send(result);
	});
	
};

exports.getAccess = function(req, res, connection) {
	item.selAccess(connection, null, function(rows) {
		res.send(rows);
	});
};
